package com.minivision.sdktestdemo.model;

import com.minivision.sdktestdemo.bean.KeyBean;
import com.minivision.sdktestdemo.bean.MusicBean;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by devtang on 2016/5/19.
 */
public abstract class GroupProvider extends Provider<KeyBean> {
    protected MusicProvider mProvider;

    public GroupProvider(MusicProvider provider) {
        mProvider = provider;
        mList = getClassfiedList(provider);
    }

    @Override
    public int remove(KeyBean data, boolean isDeletedFlag) {
        mList.remove(data);
        return mProvider.remove(data.getmListSongs(), isDeletedFlag);
    }

    //当删除单个时,调用
    public void remove(MusicBean bean) {
        int index = 0;
        for (KeyBean item : mList) {
            if (item.getmListSongs().contains(bean)) {
                item.getmListSongs().remove(bean);
                if (item.getmListSongs().size() != 0) {
                    index = -1;
                }
                break;
            }
            ++index;
        }
        if (index != -1 && index < mList.size()) {
            mList.remove(index);
        }
        setChanged(true);
    }

    //当删除多个时,调用
    public void remove(List<MusicBean> bean) {
        //仅仅是从内存上根据删除的音乐来调整分组
        Set<MusicBean> set = new HashSet<>(bean);
        List<KeyBean> temp = new ArrayList<>();
        for (KeyBean item : mList) {
            List<MusicBean> list = new ArrayList<>();
            for (MusicBean b : item.getmListSongs()) {
                if (set.contains(b)) {
                    list.add(b);
                }
            }
            for (MusicBean b : list) {
                item.getmListSongs().remove(b);
            }
            if (item.getmListSongs().size() != 0) {
                temp.add(item);
            }
        }
        setChanged(true);
        mList = temp;
    }

    public int insert(MusicBean bean, String key) {
        int index = 0;
        for (KeyBean item : mList) {
            if (item.getKey().equals(key)) {
                item.getmListSongs().add(bean);
                return index;
            }
            ++index;
        }
        if (index == mList.size()) {
            List<MusicBean> list = new ArrayList<>();
            list.add(bean);
            mList.add(new KeyBean(key, list, bean.getmPicUri()));
            sort(mList);
        }
        return index;
    }

    @Override
    public void update() {
        if (mList.size() == 0) {
            mList.addAll(getClassfiedList(mProvider));
            sort(mList);
            setChanged(true);
        }
    }

    public int update(MusicBean bean, String key) {
        remove(bean);
        insert(bean, key);
        return 0;
    }
}
